/*
 * init.c
 *
 *  Created on: Jan 29, 2013
 *      Author: justin
 */

#include "project_header.h"
#include <avr/interrupt.h>
#include <util/setbaud.h>


volatile unsigned int tick_ms; /*ticker delay counter*/
static unsigned int reload;

void init_io() {
	PORTF = 0xff;
}
void init_uart(unsigned int u) {
#if defined UBRR0H
     // get the values from the setbaud tool

     UBRR0H = UBRRH_VALUE;
     UBRR0L = UBRRL_VALUE;
 #else
 #error "Device is not supported by the driver"
 #endif

 #if USE_2X
     UCSR0A |= (1 << U2X0);
 #endif

     // enable RX and TX and set interrupts on rx complete
     UCSR0B = (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);

     // 8-bit, 1 stop bit, no parity, asynchronous UART
     UCSR0C = (1 << UCSZ01) | (1 << UCSZ00) | (0 << USBS0) |
             (0 << UPM01) | (0 << UPM00) | (0 << UMSEL01) |
             (0 << UMSEL00);

     // initialize the in and out buffer for the UART
//     ring_buffer_out = ring_buffer_init(out_buffer, BUFFER_SIZE);
//     ring_buffer_in = ring_buffer_init(in_buffer, BUFFER_SIZE);

}
int uart_out(char ch){//, FILE* stream) {
	while ((UCSR0A & (1<<UDRE))==0);  /*for xmitter empty*/
	UDR0 = ch;

	return (0);
}
/*init ticker delay time*/
void init_ticker(unsigned int usecs) {
	reload = usecs / 10; /*calc reload number*/
	TCCR0A = 0b00000011; /*prescale = 64*/
	TCNT0 = reload;	 /*load for 1st time out*/
	TIMSK0 = 0x1; /*T0 OV enabled*/
	SREG = (SREG | 0x80); /*enable interrupts*/
	sei();
}



ISR(TIMER0_OVF_vect)    //not sure why there is a default return type on
{    //non-returning function.
	TCNT0 = 256 - reload; /*set for next tick*/
	if (tick_ms > 0) /*decrement tick counter*/
	{
		tick_ms = tick_ms - 1;
	} /*end tick decrementer*/

}
